<template>
  <div class="p-8 max-w-3xl mx-auto">
    <h1 class="text-2xl font-bold mb-4">随机数生成器</h1>
    <p class="text-gray-600 mb-6">在指定范围内生成随机数，支持整数/浮点、数量、去重和小数位控制。</p>

    <div class="mb-6 grid grid-cols-1 sm:grid-cols-2 gap-4">
      <div>
        <label class="block text-sm text-gray-700 mb-1">最小值</label>
        <input type="number" v-model.number="min" class="w-full px-3 py-2 border rounded" />
      </div>
      <div>
        <label class="block text-sm text-gray-700 mb-1">最大值</label>
        <input type="number" v-model.number="max" class="w-full px-3 py-2 border rounded" />
      </div>
    </div>

    <div class="mb-6 grid grid-cols-1 sm:grid-cols-3 gap-4 items-end">
      <div>
        <label class="block text-sm text-gray-700 mb-1">数量</label>
        <input type="number" v-model.number="count" min="1" class="w-32 px-2 py-1 border rounded" />
      </div>

      <div>
        <label class="block text-sm text-gray-700 mb-1">模式</label>
        <select v-model="mode" class="w-40 px-2 py-1 border rounded">
          <option value="int">整数</option>
          <option value="float">浮点</option>
        </select>
      </div>

      <div v-if="mode === 'float'">
        <label class="block text-sm text-gray-700 mb-1">小数位</label>
        <input type="number" v-model.number="precision" min="0" max="10" class="w-24 px-2 py-1 border rounded" />
      </div>
    </div>

    <div class="mb-6 flex items-center gap-4">
      <label class="inline-flex items-center"><input type="checkbox" v-model="unique" class="mr-2"> 去重</label>
      <label class="inline-flex items-center"><input type="checkbox" v-model="useSecure" class="mr-2"> 使用安全随机（若支持）</label>
    </div>

    <div class="mb-6">
      <div class="flex items-center gap-2">
        <input v-model="resultText" readonly class="flex-1 px-3 py-2 border rounded bg-gray-50" />
        <button @click="copyResult" class="px-3 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">复制</button>
        <button @click="generate" class="px-3 py-2 border rounded hover:bg-gray-100">生成</button>
      </div>
      <p v-if="copySuccess" class="text-sm text-green-600 mt-2">已复制到剪贴板</p>
      <p v-if="error" class="text-sm text-red-600 mt-2">{{ error }}</p>
    </div>

    <div class="mb-6">
      <label class="block text-sm text-gray-700 mb-2">历史</label>
      <div v-if="history.length === 0" class="text-gray-500">暂无历史记录</div>
      <ul class="space-y-2">
        <li v-for="(h, idx) in history" :key="idx" class="flex items-center gap-2">
          <span class="flex-1 font-mono text-sm break-all">{{ h.join(', ') }}</span>
          <button @click="copyHistory(idx)" class="px-2 py-1 border rounded text-sm">复制</button>
          <button @click="removeHistory(idx)" class="px-2 py-1 border rounded text-sm">删除</button>
        </li>
      </ul>
    </div>

    <div class="flex items-center gap-3">
      <NuxtLink to="/generator-tools" class="text-blue-600 hover:underline">返回生成工具列表</NuxtLink>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useTools } from '@/composables/useTools'
useHead({ title: '随机数生成器 - 八八在线工具' })

const { copyToClipboard } = useTools()

const min = ref(0)
const max = ref(100)
const count = ref(1)
const mode = ref('int') // 'int' | 'float'
const precision = ref(2)
const unique = ref(false)
const useSecure = ref(true)

const resultText = ref('')
const history = ref([])
const copySuccess = ref(false)
const error = ref('')

function secureRandom() {
  if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
    const arr = new Uint32Array(1)
    crypto.getRandomValues(arr)
    return arr[0] / 0xffffffff
  }
  return Math.random()
}

function randomInRange(minV, maxV) {
  const r = useSecure.value ? secureRandom() : Math.random()
  return minV + r * (maxV - minV)
}

function generate() {
  error.value = ''
  copySuccess.value = false
  const a = Number(min.value)
  const b = Number(max.value)
  const n = Number(count.value) || 1
  const prec = Number(precision.value) || 0

  if (!isFinite(a) || !isFinite(b)) {
    error.value = '最小值和最大值必须是有效数字'
    return
  }
  if (a > b) {
    error.value = '最小值不能大于最大值'
    return
  }
  if (n < 1 || n > 1000) {
    error.value = '数量应在 1 到 1000 之间'
    return
  }
  if (mode.value === 'float' && (prec < 0 || prec > 10)) {
    error.value = '小数位应在 0 到 10 之间'
    return
  }

  const out = []
  const seen = new Set()
  const intMode = mode.value === 'int'

  // When unique and integer, ensure range has enough unique values
  if (unique.value && intMode) {
    const possible = Math.floor(b) - Math.ceil(a) + 1
    if (possible < n) {
      error.value = '范围内可用的唯一整数不足，请扩大范围或取消去重'
      return
    }
  }

  let attempts = 0
  while (out.length < n) {
    if (attempts++ > n * 10 + 1000) {
      error.value = '生成失败：尝试次数过多'
      break
    }
    let val = randomInRange(a, b)
    if (intMode) val = Math.floor(val + 0.0000001)
    else val = Number(val.toFixed(prec))

    const key = intMode ? String(val) : val.toFixed(prec)
    if (unique.value) {
      if (seen.has(key)) continue
      seen.add(key)
    }
    out.push(mode.value === 'int' ? Number(key) : Number(key))
  }

  resultText.value = out.join(', ')
  history.value.unshift(out.slice())
  if (history.value.length > 20) history.value.pop()
}

async function copyResult() {
  if (!resultText.value) return
  const ok = await copyToClipboard(resultText.value)
  if (ok) {
    copySuccess.value = true
    setTimeout(() => (copySuccess.value = false), 1500)
  }
}

async function copyHistory(idx) {
  const arr = history.value[idx]
  if (!arr) return
  const ok = await copyToClipboard(arr.join(', '))
  if (ok) {
    copySuccess.value = true
    setTimeout(() => (copySuccess.value = false), 1500)
  }
}

function removeHistory(idx) {
  history.value.splice(idx, 1)
}

// 生成一个初始示例
generate()
</script>

<style scoped>
</style>
